package com.pai4j.search.messagequeue.consumer;

import com.pai4j.common.enums.ESMessageTypeEum;
import com.pai4j.common.enums.messagequeue.MessageQueueEnum;
import com.pai4j.common.service.messagequeue.consumer.AbstractRedisQueueConsumer;
import com.pai4j.common.util.JsonUtil;
import com.pai4j.domain.vo.dto.AbstractESMessageDTO;
import com.pai4j.domain.vo.response.UserBaseResponseInfoVO;
import com.pai4j.search.service.es.AccountElasticSearchService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 账号信息同步ES消费者
 */
@Slf4j
@Component
@Lazy(false)
public class AccountSyncRedisQueueConsumer extends AbstractRedisQueueConsumer<UserBaseResponseInfoVO> {

    @Resource
    private AccountElasticSearchService accountElasticSearchService;

    public void initBean() {

        new Thread(() -> schedule()).start();
    }

    @Override
    protected UserBaseResponseInfoVO convert(String s) {
        return JsonUtil.fromJson(s, UserBaseResponseInfoVO.class);
    }

    @Override
    protected MessageQueueEnum getMessageQueue() {
        return MessageQueueEnum.QUEUE_ACCOUNT_SYNC_ES;
    }

    @Override
    protected void receive(UserBaseResponseInfoVO account) throws Exception {
        accountElasticSearchService.sync(buildAccountESMessage(account));
    }

    private AbstractESMessageDTO buildAccountESMessage(UserBaseResponseInfoVO account) {
        AbstractESMessageDTO dto = new AbstractESMessageDTO();
        dto.setType(ESMessageTypeEum.ACCOUNT.getType());
        dto.setBizId(account.getUserId());
        // 可搜索内容：用户名 + 个性签名
        StringBuilder content = new StringBuilder();
        if (StringUtils.isNotBlank(account.getUserName())) {
            content.append(account.getUserName());
        }
        if (StringUtils.isNotBlank(account.getSignature())) {
            if (content.length() > 0) content.append(":");
            content.append(account.getSignature());
        }
        dto.setContent(content.toString());
        dto.setData(JsonUtil.toJsonString(account));
        Date now = new Date();
        dto.setCreateDate(now);
        dto.setUpdateDate(now);
        return dto;
    }

    @Override
    protected void error(UserBaseResponseInfoVO data, Exception ex) {
        backToQueue(data);
        log.error("AccountSyncRedisQueueConsumer error", ex);
    }
}
